<?php

namespace app\index\controller;
use app\admin\model\Admin;
use app\admin\model\Area;
use app\admin\model\Githouse;
use app\admin\model\halt\Cate;
use app\admin\model\orders\Shopping;
use app\admin\model\Preproduct;
use app\common\controller\Frontend;
use app\common\model\order\Order;
use app\common\model\order\Orderitem;
use app\common\model\order\Orderlog;
use EasyWeChat\Factory;
use think\Cookie;
use think\Hook;
use think\Session;

class Goods extends Frontend
{
    //无需登录的方法,同时也就不需要鉴权了
    protected $noNeedLogin = 'login,test,addressEdit,addAddress,setAddress';
    //无需鉴权  但是需要登录
    protected $noNeedRight = 'addressEdit,addAddress';
    //布局模板
    protected $layout = 'default';
    //登录url
    protected $loginUrl = 'goods/login';

    protected $user;

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;
        $this->user = $this->auth->getUser();
        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        $this->view->assign('user',$this->user);
        $this->view->assign('count',Shopping::where(['userid'=>$this->user['userid']])->count());
        $cateList = Cate::field('id,pid,name,type')->order('type','desc')->select();
        $cateList = generateTree(getTree(collection($cateList)->toArray()));
        $this->view->assign('cateList',$cateList);
    }

    public function index()
    {
        //获取商品列表
        list($where, $sort, $order, $offset,$limit,$page,$classif,$url,$search) = $this->buildparams();
        $total = Preproduct::with('cate')
            ->where($where)
            ->order($sort, $order)
            ->count();
        $list = Preproduct::with('cate')
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();
        $result = array("total" => $total, "rows" => $list);
        $this->view->assign('result',$result);
        $obj = (object) explode(',',$classif) ;
        $this->view->assign('classif',json_encode($obj));
        $this->view->assign('keyField',['where'=>$where,'offset'=>$offset,'page'=>$page,'classif'=>$classif,'url'=>$url,'search'=>$search]);
        return $this->view->fetch();
    }

    /**
     * 搜索
     * @return array
     */
    protected function buildparams()
    {
        $search = $this->request->get("name", '');
        $sort = $this->request->get("sort", "preproduct.id");
        $order = $this->request->get("order", "DESC");
        $page = $this->request->get("page", 1);
        $classif = $this->request->get('classif','');
        $url = $this->request->get('s','');
        $url .= "?";
        $where = [];
        if($classif)
        {
            $where = [
                'preproduct.class_text'  =>  ['like',"%{$classif}%"],
            ];
            $url  .="classif={$classif}&";
        }
        if($search)
        {
            $where['preproduct.cname|cate.name'] = ['like',"%{$search}%"];
        }
        if(!$page || $page ==1)
        {
            $offset = 0;
            $limit = 12;
            $url  .="page=1&";
        }else{
            $offset = ($page - 1) * 12;
            $limit = ($page-1 * 12) + 12;
            $url  .="{$page}&";
        }
        return [$where, $sort, $order, $offset, $limit, $page, $classif, $url, $search];
    }

    /**
     * 收货地址列表
     * @return string|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addressEdit($ids=null)
    {
        $this->layout = 'address_edit';
        if($this->request->isAjax())
        {
            $row = Githouse::get($this->request->request('id',0));
            //下单选择收货地址
            return json($row);
        }
        if(!$this->user['department'])
        {
            $row = Order::get($ids);
            $this->user['department'] = $row->dep_id;
        }
        //收货地址列表
        $list = Githouse::where('dep',$this->user['department'])->order('default','desc')->select();
        $this->view->assign('list',$list);
        $this->view->assign('ids',$ids);
        return $this->view->fetch('address_edit');
    }

    /**
     * 添加  修改 收货地址
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function addAddress()
    {
        if($this->request->isAjax())
        {
            $row = $this->request->request();
            unset($row['s']);
            if(!empty($row['id'])) //修改
            {
                $githouse = Githouse::get($row['id']);
                $githouse->lxr = $row['lxr'];
                $githouse->mobile = $row['mobile'];
                $githouse->province = $row['province'];
                $githouse->city = $row['city'];
                $githouse->area = $row['area'];
                $githouse->address = $row['address'];
                if(!$githouse->save())
                {
                    return json(['msg'=>'保存失败','status'=>1]);
                }
            }else{
                unset($row['id']);
                $row['dep'] = $this->user['department'] ? $this->user['department'] : Session::get('admin.department');
                $row['gname'] = $this->user['department_text'] ? $this->user['department_text'] : Session::get('admin.department_text');
                $githouse = new Githouse;
                $githouse->data($row);
                if(!$githouse->save())
                {
                    return json(['msg'=>'保存失败','status'=>1]);
                }
            }
            return json(['msg'=>'保存成功','status'=>0]);
        }
    }

    /**
     * 设置默认地址
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function setAddress()
    {
        if($this->request->isAjax('POST'))
        {
            $row = Githouse::get($this->request->request('id'));
            //订单修改收货地址
            $ids = $this->request->request('ids',0);
            if($ids > 0)
            {
                $orderRow = Order::get($ids);
                $orderRow->githouse_id = $row->id;
                $orderRow->save();
                //提交订货单日志 没审核之前是可以修改的收货信息的

                Orderlog::create([
                    'order_id'=>$ids,
                    'dep_name'=>$this->user['department_text'] ? $this->user['department_text'] :Session::get('admin.department_text'),
                    'dep_id'=>$this->user['department'] ? $this->user['department'] : Session::get('admin.department'),
                    'userid'=>$this->user['userid'] ? $this->user['userid'] : Session::get('admin.userid') ,
                    'username'=>$this->user['username'] ? $this->user['username'] : Session::get('admin.username'),
                    'content'=>'修改订货单地址',
                    'type'=>1,
                ]);
            }
            if($this->request->request('action') == 'set')
            {
                return json(['msg'=>'操作成功！','status'=>0,'data'=>$row]);
            }
            Githouse::where('dep',$this->user['department']?$this->user['department']:Session::get('admin.department'))->update(['default'=>0]);
            $row->default = 1;
            if(!$row->save())
            {
                return json(['msg'=>'设置默认地址失败！','status'=>1]);
            }
            return json(['msg'=>'设置默认地址成功！','status'=>0,'data'=>$row]);
        }
        return json(['msg'=>'没有参数！','status'=>1]);
    }

    //添加到购物车
    public function add()
    {
        if($this->request->isAjax('post'))
        {
            if(!$goodsid = $this->request->request('id'))
            {
                return json(['msg'=>'缺少产品ID']);
            }
            $number = intval($this->request->request('number'));
            if($number <= 0)
            {
                return json(['msg'=>'缺少数量']);
            }
            $shoppingRow = Shopping::get(function($query) use ($goodsid){
                $query->where(['userid'=>$this->user['userid'],'fid'=>$goodsid]);
            });
            if($shoppingRow)
            {
                $shoppingRow->number += $number;
                $shoppingRow->save();
                return json(['msg'=>'成功追加到购物车']);
            }
            if(!$res = Shopping::create(['userid'=>$this->user['userid'],'number'=>$number,'fid'=>$goodsid,'department_id'=>$this->user['department']]))
            {
                return json(['msg'=>'添加购物车失败！']);
            }
        }
        return json(['msg'=>'已添加到购物车','count'=>Shopping::where(['userid'=>$this->user['userid']])->count()]);
    }

    /**
     * 购物车
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function card()
    {
        $shoppingCartList = Shopping::alias('a')
            ->field('a.id as sid,a.*,b.*,c.*')
            ->where(['a.userid'=>$this->user['userid']])
            ->join('hdyj_preproduct b','a.fid = b.id')
            ->join('hdyj_halt_cate c','b.classif = c.id')
            ->select();
        $this->view->assign('shoppingCartList',$shoppingCartList);
        return $this->view->fetch();
    }

    /**
     * 商品详情
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function info($ids)
    {
        $row = Preproduct::get($ids);
        $this->view->assign('row',$row);
        return $this->view->fetch();
    }

    /**
     * 确认下单
     */
    public function andorder()
    {
        if($this->request->request('shoppingcar'))
        {
            return json(['count'=>Shopping::where(['userid'=>$this->user['userid']])->count()]);
        }
        $shoppingCartList = Shopping::alias('a')
            ->field('a.id as sid,a.*,b.*,c.*')
            ->where(['a.userid'=>$this->user['userid']])
            ->join('hdyj_preproduct b','a.fid = b.id')
            ->join('hdyj_halt_cate c','b.classif = c.id')
            ->select();
        $this->view->assign('shoppingCartList',$shoppingCartList);
        $default = Githouse::get(function ($query){
           $query->where(['dep'  => $this->user['department'], 'default'=>  1]);
        });
        if($default)
        {
            $default = $default->toArray();
        }
        $this->view->assign('default',$default);
        return $this->view->fetch();
    }

    /**
     * 修改备注购物车 订单详情备注,修改
     * @param $ids
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function remark($ids = null)
    {
        if($this->request->isAjax())
        {
            if(!$ids)
            {
                $order_id = $this->request->request('order_id');
                $preproduct_id = $this->request->request('preproduct_id');
                $remark = $this->request->request('content');
                //修改订单备注
                if($order_id && $remark && empty($preproduct_id))
                {
                    $orderRow = Order::get($order_id);
                    $orderRow->remark = $remark;
                    $orderRow->save();
                }
                if($order_id && $remark && $preproduct_id)
                {
                    $orderItem = new Orderitem;
                    $orderItem->where(['order_id'=>$order_id,'preproduct_id'=>$preproduct_id])->update(['remark'=>$remark]);
                }
                return json(['msg'=>'修改成功']);
            }

            if($remark = $this->request->request('remark'))
            {
                $row = Shopping::get($ids);
                if($row)
                {
                    $row->remark = $remark;
                    if($row->save())
                    {
                        return json(['msg'=>'修改备注成功']);
                    }
                }
                return json(['msg'=>'没有修改备注']);
            }
        }
        return json(['msg'=>'参数有误！']);
    }

    /** 删除单个  或多个购物车商品
     * @return \think\response\Json
     */
    public function clearCart()
    {
        if($this->request->request('status') == 'clearCart')
        {
            $res = Shopping::destroy(function($query){
                $query->where(['userid'=>$this->user['userid']]);
            });
            $data = ['msg'=>'清空购物车成功！','status'=>0];
        }
        if($this->request->request('id') > 0)
        {
            $res = Shopping::destroy(intval($this->request->request('id')));
            $data = ['msg'=>'删除成功！','count'=>Shopping::where(['userid'=>$this->user['userid']])->count(),'status'=>0];
        }
        if($res >= 1)
        {
            return json($data);
        }
        return json(['msg'=>'操作失败！','status'=>1]);
    }

    /**
     * 修改购物车数量
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function updateCard()
    {
        if(!$cid = $this->request->request('cid'))
        {
            return json(['msg'=>'缺少购物车ID']);
        }
        $number = intval($this->request->request('number'));
        if($number <= 0)
        {
            return json(['msg'=>'缺少数量']);
        }
        $row = Shopping::get($cid);
        $row->number = $number;
        $row->save();
        return json(['msg'=>'修改成功！']);
    }

    /**
     *查看订单
     * @return string
     * @throws \think\Exception
     */
    public function order()
    {
        //获取订单列表
        list($where, $sort, $order, $offset,$limit,$search,$pageSize,$currentPage) = $this->orderBuildparams();
        $total = Order::with(['githouse','orderlog'])->where($where)
            ->order($sort, $order)
            ->count();
        $list = Order::with(
            ['githouse'=>function($query){
                $query->field('dep,gname,id,status,ctime,lxr,mobile,province,city,area,address');
            },'orderlog'=>function($query){
                $query->field('order_id,username,content,updatetime');
            }])
            ->where($where)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();
        $result = array("total" => $total, "rows" => $list);
        $this->view->assign('result',$result);
        $this->view->assign('where',['pageSize'=>$pageSize,'currentPage'=>$currentPage]);
        return $this->view->fetch();

    }

    protected function orderBuildparams()
    {
        $search = $this->request->get("name", '');
        $sort = $this->request->get("sort", "id");
        $order = $this->request->get("order", "DESC");
        $offset  = $this->request->get("offset", 0);//分页
        $limit = $this->request->get("limit", 10);
        $pageSize = $this->request->get('pageSize',10);//页大小
        $currentPage = $this->request->get('currentPage',1);//当前页
        if($currentPage == 1)
        {
            $offset = 0;
            $limit = $pageSize;
        }
        if($currentPage > 1)
        {
            $offset = ($currentPage - 1) * $pageSize;
            $limit = $pageSize * $currentPage;
        }
        $where = ['dep_id'=>$this->user['department']];//当前所在的公司
        return [$where, $sort, $order, $offset, $limit, $search, $pageSize, $currentPage];
    }

    /**
     * 生成订单
     */
    public function addOrder()
    {
        if($this->request->isPost())
        {
            $row['remark'] = $this->request->request('remark','');
            $row['githouse_id'] = $this->request->request('addressid',0);
            $row['deliverydate'] = $this->request->request('time');
            $row['dep_id'] = $this->user['department'];
            $row['nb'] = getOrderNo('DH-O');
            $row['userid'] = $this->user['userid'];
            //获取购物车商品
            $orderId = Order::create($row)->getLastInsID();
            //生产订单
            $shoppingList = Shopping::where(['userid'=>$this->user['userid']])->column('id as preproduct_id,number as num,remark');
            $orderItem = new Orderitem();
            $orderItemArray = [];
            if($shoppingList)
            {
                foreach ($shoppingList as $preproduct_id=>$value)
                {
                    $value['order_id'] = $orderId;
                    $orderItemArray[] = $value;
                }
            }
            //生产订单详情
            $orderRes = $orderItem->saveAll($orderItemArray,false);
            if($orderRes)
            {
                //提交订货单日志
                Orderlog::create([
                    'order_id'=>$orderId,
                    'dep_name'=>$this->user['department_text'],
                    'dep_id'=>$this->user['department'],
                    'userid'=>$this->user['userid'],
                    'username'=>$this->user['username'],
                    'content'=>'已提交订货单，等待订货单审核',
                    'type'=>1,
                ]);
                //清空购物车
                Shopping::destroy(function($query){
                    $query->where(['userid'=>$this->user['userid']]);
                });
                $this->redirect('orderInfo', ['ids' => $orderId]);
            }
        }
    }

    /**
     * 订单详情
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderInfo($ids)
    {
        if($order = Order::get($ids))
        {
            $Githouse = Githouse::get($order->githouse_id);
            $orderList = Orderitem::alias('a')
                ->field('a.*,a.remark as remarks,b.*')
                ->where('a.order_id',$ids)
                ->join('hdyj_preproduct b','a.preproduct_id = b.id')
                ->select();
            $order = $order->toArray();
            $order['userid_text'] = Admin::userName($order['userid']);
            $orderlogList = Orderlog::where('order_id',$ids)->select();
            $this->view->assign('orderlogList',$orderlogList);
            $this->view->assign('Githouse',$Githouse);
            $this->view->assign('order',$order);
            $this->view->assign('orderList',$orderList);
        }
        return $this->view->fetch();
    }

    /**
     * 要货登录
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function login()
    {
        $config = \app\admin\model\orders\Goods::WechatConfig();
        $app = Factory::work($config);
        $code = $this->request->request('code');
        $token = $app->access_token->getToken();//获取企业微信token
        //企业微信端登录
        if(\think\Request::instance()->isMobile())
        {
            if(!$code) $this->redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$config['corp_id']."&redirect_uri=".$config['oauth']['callback']."&response_type=code&scope=".$config['oauth']['scopes']."&agentid=".$config['agent_id']."&state=STATE#wechat_redirect");
        }else{
            if(!$code) $this->redirect("https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid={$config['corp_id']}&agentid={$config['agent_id']}&redirect_uri={$config['oauth']['callback']}&state=fc62");
        }
        $user = \fast\Http::get($url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}");
        $user = json_decode($user,true);
        $this->auth->wechatLogin($user['UserId']) ? $this->redirect('goods/index') : $this->error('登录信息有误，请联系管理员');
    }

    public function test()
    {
        $this->auth->wechatLogin('1')? $this->redirect('goods/index') : $this->error('登录信息有误，请联系管理员');
    }
}
